<?php

namespace pc\models;

use common\helpers\ChineseSpell;
use common\Service\RedisService;
use Yii;
use common\models\Portray as P_Portray;


/**
 * This is the model class for table "{{%portray}}".
 *
 * @property string $id
 * @property string $title
 * @property string $desc
 * @property string $images
 * @property integer $star_id
 * @property integer $create_time
 * @property integer $image_num
 * @property integer $status
 * @property string $tags
 * @property integer $view
 */
class Portray extends P_Portray
{

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => '标题',
            'desc' => '描述',
            'images' => '图片',
            'star_id' => '明星编号',
            'create_time' => '添加时间',
            'image_num' => '图片数量',
            'status' => '状态 1：显示 2：不显示',
            'tags' => '标签',
            'view' => '浏览量',
        ];
    }

    /**
     *  设置写真HASH，干掉名字标签
     *  TODO 设置封面图
     */
    public function setPortrayHash(){
        $redis = Yii::$app->get('redis');
        $portrayId = (int)$redis->get('portrayId');

        $sqlCommand = "SELECT a.* ,b.name,b.nick_name FROM {{%portray}} a LEFT JOIN {{%star}} b ON a.`star_id` = b.id  WHERE a.id > {$portrayId} LIMIT 3000";
        $data = Yii::$app->db->createCommand($sqlCommand)->queryAll();
        if(empty($data)) echo 'ok';
        foreach ($data as &$portray){
            $starName = $portray['name'].','.$portray['nick_name'];
            $starName = explode(',',$starName);
            foreach ($starName as $name){
                if(!empty($name)){
                    $portray['tags'] = str_replace(trim($name),'',$portray['tags']);
                }
            }
            $portray['tags'] = explode(',',$portray['tags']);
            $portray['tags']  = $this->filter($portray['tags']);
            $portray['tags']  = implode(',',$portray['tags']);

            $por = Portray::findOne(intval($portray['id']));
            if($por){
               $por->tags = $portray['tags'];
               $por->save();
               $redis->set('portrayId',intval($portray['id']));
               unset($portray['name']);
               unset($portray['nick_name']);
               RedisService::setHash('portray:'.intval($portray['id']),$portray);
               $redis->set('portrayId',intval($portray['id']));
            }

        }
        unset($portray);
        echo 'ok';
    }

    /**
     * 干掉数据中的空数据
     * @param array $arr
     * @return array
     */
    private function filter($arr = []){
        $rs = [];
        foreach ($arr as $vo){
            if(!empty($vo)) $rs[] = trim($vo);
        }
        return $rs;
    }

    /**
     * 初始化标签关联写真数据 标签生成缩写写入数据库
     */
    public function insertTagToMysql(){
        $redis = Yii::$app->get('redis');

//        先把所有的标签清理出来，放入一个集合统计每个标签关联的写真数目
//        for($i = 666; $i < 9635; $i++){
//            $portray = RedisService::getHash('portray:'.$i,['id','tags']);
//            if($portray){
//                $portray['tags'] = explode(',',$portray['tags']);
//                foreach ($portray['tags'] as $tag){
//                    $redis->zincrby('portrayTagsZset',1,trim($tag));
//                }
//            }
//        }
//        exit;

        //根据之前统计的标签关联写真数目，关联数大于等于6的保存的数据库 其他的保存到otherxiezhen
        $tags = RedisService::zRange('portrayTagsZset');
        $resultTags = [];
        $chineseSpell = new ChineseSpell();
        $i = 0;
        foreach($tags as $name => $num){
            if($num < 6){
                $this->setOtherTag($name);
                continue;
            }
            $tag = Tags::find()->where(['name' => trim($name)])->andWhere(['<','id',1005])->one();
            if($tag){
                $tag->setAttribute('category',0);
                $tag->save();
                continue;
            }

            $tmp['name'] = $name;
            $tmp['alias'] = $chineseSpell->getFullSpell(iconv('UTF-8','GBK',$name));
            $tmp['type'] = 0;
            $tmp['sort'] = $num;
            $tmp['status'] = 1;
            $tmp['category'] = 2;
            $resultTags[] = $tmp;
            $tag = new Tags();
            $tag->loadDefaultValues();
            $tag->setAttributes($tmp,false);

            $tag->save();
        }

        print_r($resultTags);
        echo 'ok';
    }

    private function setOtherTag($tag = ''){
        if(empty($tag)) return;
        Yii::$app->get('redis')->sadd('otherTagNames',trim($tag));
    }

    /**
     * 寫真redis設置HASH和总榜
     */
    public function setRedis(){
        $redis = Yii::$app->get('redis');
        $portrayId = (int)$redis->get('portrayId');

        $sqlCommand = "SELECT a.*,relation_star as restar FROM {{%portray}} a WHERE id > {$portrayId} LIMIT 2000";
        $data = Yii::$app->db->createCommand($sqlCommand)->queryAll();
        if(empty($data)) echo 'ok';

        foreach ($data as &$pt){
            $pt['tags'] = explode(',',$pt['tags']);
            if(!empty($pt['tags'])){
                $pt['relation_star'] = $pt['newTags'] = [];
                foreach ($pt['tags'] as $tag){
                    if(!empty($tag)){
                        $starId = (int)$redis->hget('starNameIds',trim($tag));
                        if($starId > 0){ //表示是明星的名字
                            !in_array($starId,$pt['relation_star']) && $pt['relation_star'][] = $starId;
                        }else{ //常规标签
                            !in_array(trim($tag),$pt['newTags']) && $pt['newTags'][] = trim($tag);
                        }
                    }
                }
            }

            //更新到数据库 设置redis
            $model = Portray::findOne(intval($pt['id']));
            if($model){
                $_tags = implode(',',$pt['newTags']);
                $_stars = implode(',',$pt['relation_star']);
                !empty($_tags) && $model->setAttribute('tags',$_tags);
                !empty($_stars) && $model->setAttribute('relation_star',$_stars);
                $model->save();
                RedisService::setHash('portray:'.intval($pt['id']),[
                    'id'=>intval($pt['id']),
                    'tags' => $_tags,
                    'relation_star' => $pt['restar'],
                    'title' => $pt['title'],
                    'desc' => $pt['desc'],
                    'images' => $pt['images'],
                    'star_id' => $pt['star_id'],
                    'create_time' => $pt['create_time'],
                    'image_num' => $pt['image_num'],
                    'status' => $pt['status'],
                    'view' => $pt['view'],
                ]);
                $redis->set('portrayId',intval($pt['id']));
                $redis->zadd('portrayZset',intval($pt['view']),intval($pt['id']));
            }

        }
        unset($pt);
//        print_r($data);
        echo 'ok';
    }


    /*
     * 设置明星和写真集的相关关系，以及设置标签和写真集的关系
     */
    public function setStarTagRelation(){
        $redis = Yii::$app->get('redis');
        $portrayId = (int)$redis->get('portrayId');

        $portrays = Portray::find()
            ->select(['id','tags','relation_star','view'])
            ->where(['>' , 'id' , $portrayId])
            ->limit(2000)
            ->asArray()
            ->all();

        if(empty($portrays)) echo 'ok';

        foreach($portrays as $portray){
            $tags = explode(',',$portray['tags']);
            $starIds = explode(',',$portray['relation_star']);
            $tags = $this->filter($tags);
            $starIds = $this->filter($starIds);

            if($tags) {
                //设置标签关联的写真
                $tagsInfo = Tags::find()
                    ->select(['name', 'alias'])
                    ->where(['in', 'name', $tags])
                    ->asArray()
                    ->indexBy('name')
                    ->all();

                foreach ($tags as $tag) {
                    if ((int)$redis->sismember('otherTagNames', trim($tag)) == 1 || !isset($tagsInfo[$tag])) {
                        $redis->zadd('otherTagPortrayZset', intval($portray['view']), intval($portray['id']));
                    } else {
                        $redis->zadd('tagPortrayZset:' . $tagsInfo[trim($tag)]['alias'], intval($portray['view']), intval($portray['id']));
                    }
                }
                unset($tagsInfo);
            }

            //设置明星关联的写真
            foreach($starIds as $starId){
                $redis->sadd('tagPortraySet:'.intval($starId),intval($portray['id']));
            }
            $redis->set('portrayId',$portray['id']);
        }

        echo 'ok';
    }



}
